﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using Kiva7.Utilities;
using Kiva7.DataRequests;
using Kiva7.DataClasses;
using Kiva7.Controls;
using Microsoft.Phone.Controls.Maps;
using Kiva7.Translations;
using Kiva7.Images;
using Kiva7.Constants;

namespace Kiva7.Pages
{
    public partial class SearchLoanDetailPage
    {
        private const string Url = "/Pages/SearchLoanDetailPage.xaml";
        public readonly static Uri PageUrl = new Uri(Url, UriKind.RelativeOrAbsolute);

        public static Uri GetPageUrl(IEnumerable<Loan> loanList, int index)
        {
            if (loanList == null)
                return null;

            List<int> list = loanList.Select(loan => loan.Id).ToList();

            UrlCreator url = new UrlCreator(Url);
            url.Add(CacheGuidKey, CacheIdList(list));

            url.Add(IndexKey, index);

            return url.ToUri(UriKind.RelativeOrAbsolute);
        }

        public SearchLoanDetailPage()
        {
            InitializeComponent();
            CreateStandardControls();

            SetPivot(Pivot);

            
        }

        private void PhoneApplicationPageLoaded(object sender, RoutedEventArgs e)
        {
            _request = new LoanDetailRequest();
            _request.OnResponse += new DataRequest<DataResponse.LoansResponse, Loan>.DataRequestDelegate(request_OnResponse);

            DataContext = _request;

            _partnerRequest = new PartnerRequest();
            partnerDetailControl.DataContext = _partnerRequest;

            _loanLendersRequest = new LoanLendersRequest();
            lendersControl.DataContext = _loanLendersRequest;

            RequestMain();
        }

        void request_OnResponse(object sender, DataRequest<DataResponse.LoansResponse, Loan>.DataRequestEventArgs e)
        {
            if (!e.Cancelled
                && e.Exception == null)
            {
                CheckPivot(Pivot.SelectedItem as PivotItem);
            }
        }

        LoanDetailRequest _request;
        protected override void RequestMain()
        {
            if (_request.LoadStatus == LoadStatus.NotLoaded)
            {
                _request.GetLoan(IdList[Index]);
            }
        }

        PartnerRequest _partnerRequest;
        private void RequestPartner()
        {
            if (_request != null
                && _request.IsLoaded
                && _request.SingleData != null
                && _partnerRequest.Partner == null)
            {
                _partnerRequest.GetPartner(_request.SingleData.PartnerId);
            }
        }

        LoanLendersRequest _loanLendersRequest;
        private void RequestLenders()
        {
            if (_loanLendersRequest.LoadStatus == LoadStatus.NotLoaded)
            {
                _loanLendersRequest.GetLenders(IdList[Index]);
            }
        }

        private void PivotLoadingPivotItem(object sender, PivotItemEventArgs e)
        {
            CheckPivot(e.Item);
        }

        protected override void CheckPivot(PivotItem pi)
        {
            if (_BarButtonTranslate != null)
            {
                _BarButtonTranslate.IsEnabled = pi == Main;
            }

            if (pi == Lenders)
            {
                RequestLenders();
            }
            else if (pi == Partner)
            {
                RequestPartner();
            }
            else if (pi == Map)
            {
                CreateMap();
            }
        }
        private void CreateMap()
        {
            if (Map.Content == null
                && _request != null
                && _request.SingleData != null
                && _request.SingleData.Location != null
                && _request.SingleData.Location.Geo != null)
            {

                Map map = new Map
                    {
                        CredentialsProvider = new ApplicationIdCredentialsProvider(Constant.BingMapId),
                        LogoVisibility = Visibility.Collapsed,
                        CopyrightVisibility = Visibility.Collapsed,
                        ZoomLevel = 6,
                        ZoomBarVisibility = Visibility.Visible,
                        Center = _request.SingleData.Location.Geo.Coordinate
                    };

                Map.Content = map;
            }
        }
        protected override void ClearRequests()
        {
            _request.Clear();
            _partnerRequest.Clear();
            _loanLendersRequest.Clear();
        }

        private BindableApplicationBarButton _BarButtonTranslate;

        protected override void CreateApplicationBar()
        {
            AddBarButton(AppResources.Back, ImageUrls.Back, BackClick);

            _BarButtonTranslate = AddBarButton(AppResources.TranslateTexts, ImageUrls.Translation, TranslateClick);

            AddBarButton(AppResources.SendBasket, ImageUrls.SendBasket, SendBasketClick);

            AddBarButton(AppResources.Next, ImageUrls.Next, NextClick);
        }

        private void TranslateClick(object sender, EventArgs e)
        {
            LoanImageControl1.TranslateTextWithDetect();
        }


        private void SendBasketClick(object sender, EventArgs e)
        {
            if (!Baskets.Basket.Current.IsEmpty)
            {
                DoNavigate(BasketPage.PageUrl);
            }
        }
    }
}